import type { RouteRecordRaw } from 'vue-router';

export interface ModuleDefinition {
  registerRoutes: () => RouteRecordRaw[];
  onMount?: () => void;
  onUnmount?: () => void;
}

export interface ModuleConfig {
  id: string;
  name: string;
  entry: string;
  enabled: boolean;
  priority: number;
}

/**
 * 加载并初始化所有模块
 */
export const loadModules = async (): Promise<ModuleDefinition[]> => {
  try {
    // 1. 获取模块配置
    const response = await fetch('/modules.json');
    if (!response.ok) {
      throw new Error(`配置加载失败: HTTP ${response.status}`);
    }
    
    const configs: ModuleConfig[] = await response.json();
    const enabledConfigs = configs
      .filter(c => c.enabled)
      .sort((a, b) => a.priority - b.priority);
    
    const modules: ModuleDefinition[] = [];
    
    // 2. 动态加载并初始化模块
    for (const config of enabledConfigs) {
      try {
        // 动态导入模块
        const moduleModule = await import(/* @vite-ignore */ config.entry);
        
        // 验证模块接口
        if (!moduleModule?.default?.registerRoutes) {
          console.error(`[模块加载] ${config.id} 未提供 registerRoutes 函数`);
          continue;
        }
        
        const routes = moduleModule.default.registerRoutes();
        if (!routes || (Array.isArray(routes) && routes.length === 0)) {
          console.warn(`[模块加载] ${config.id} 返回空路由`);
          continue;
        }
        
        modules.push(moduleModule.default);
        
      } catch (error) {
        console.error(`[模块加载] ${config.id} 失败:`, error);
      }
    }
    
    return modules;
    
  } catch (error) {
    console.error('[模块加载器] 配置加载失败:', error);
    return [];
  }
};

/**
 * 规范化路由路径
 */
export const normalizeRoutePath = (path: string): string => {
  return path.startsWith('/') ? path.slice(1) : path;
};

// export const loadModules = async (): Promise<ModuleDefinition[]> => {
//   // 获取模块配置
//   const response = await fetch('/modules.json');
//   const configs: ModuleConfig[] = await response.json();
  
//   // 按优先级排序
//   const sortedConfigs = configs
//     .filter(c => c.enabled)
//     .sort((a, b) => a.priority - b.priority);
  
//   const modules: ModuleDefinition[] = [];
  
//   // 动态加载模块
//   for (const config of sortedConfigs) {
//     try {
//       const module = await import(/* @vite-ignore */ config.entry);
      
//       if (module && typeof module.default === 'object') {
//         modules.push(module.default);
//       } else {
//         console.error(`[模块加载] ${config.id} 模块格式无效`);
//       }
//     } catch (error) {
//       console.error(`[模块加载] ${config.id} 模块加载失败:`, error);
//     }
//   }
  
//   return modules;
// };